/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes.resources;

import com.google.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import th.config.ableContextListener;
import th.dao.KodJenisSekolahDAO;
import th.dao.KodNegeriDAO;
import th.dao.KodSekolahDAO;
import th.manager.UserManager;
import th.model.Deposit;
import th.model.KodFakulti;
import th.model.KodJenisPengajian;
import th.model.KodJenisSekolah;
import th.model.KodKahwin;
import th.model.KodNegeri;
import th.model.KodSekolah;
import th.model.KodSektorPekerjaan;
import th.model.KodTahapPengajian;
import th.model.KodUniversiti;
import th.model.Pengguna;
import th.model.PusatKos;
import th.service.session.LoginSession;
import th.service.session.SessionManager;
import th.stripes.BaseActionBean;
import th.stripes.action.TrxAuthorizationCodeActionBean;
import th.stripes.util.AccCheckUtil;
import th.stripes.util.ListUtil;

/**
 *
 * @author fikri
 */
@UrlBinding("/services/util")
public class UtilResource extends BaseActionBean implements iRest {

     @Inject
     private ListUtil listUtil;

     @Inject
     private KodNegeriDAO kodNegeriDAO;

     @Inject
     private KodJenisSekolahDAO kodJenisSekolahDAO;

     @Inject
     private KodSekolahDAO kodSekolahDAO;

     @Inject
     private UserManager user;

     @Inject
     private UserManager userManager;

     private static final String PROFILE_ENQ_MSG_ID = "TPDPPROFWD01";

     private static final String HEADER_ID_PROFILE_ENQUIRY = "THSDPQR";

     private static final String HEADER_ID_FND_TFR = "THSTHT3";

     private static final String HEADER_ID_UPD_PROFILE = "THSDPUP";

     private static final String HEADER_ID_ADD_FAV_ACC = "THFAVADD";

     private static final String HEADER_ID_EDIT_FAV_ACC = "THFAVEDIT";

     @HandlesEvent("req_all_negeri")
     public Resolution negeriInquiry() {
          List<KodNegeri> list = listUtil.getSenaraiNegeri();

          JSONArray array = new JSONArray();
          for (KodNegeri kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("kod", kod.getCode());
               obj.put("nama", kod.getDesc());
               array.put(obj);
          }

          return new StreamingResolution("application/json", array.toString());
     }
     
@HandlesEvent("req_married_status")
     public Resolution marryInquiry() {
          List<KodKahwin> list = listUtil.getSenaraiPerkahwinan();

          JSONArray array = new JSONArray();
          for (KodKahwin kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("value", kod.getKod());
               obj.put("name", kod.getNama());
               array.put(obj);
          }

          return new StreamingResolution("application/json", array.toString());
     }
          
          @HandlesEvent("req_work_sector")
     public Resolution workSectorInquiry() {
          List<KodSektorPekerjaan> list = listUtil.getSenaraiSektorPekerjaan();

          JSONArray array = new JSONArray();
          for (KodSektorPekerjaan kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("value", kod.getKod());
               obj.put("name", kod.getNama());
               array.put(obj);
          }

          return new StreamingResolution("application/json", array.toString());
     }
     
     @HandlesEvent("req_negeri_desc")
     public Resolution negeriDescInquiry() {

          String kodNegeri = getContext().getRequest().getParameter("param1");
          JSONObject obj = new JSONObject();

          if (StringUtils.isNotBlank(kodNegeri)) {
               KodNegeri kod = kodNegeriDAO.findById(kodNegeri);
               if (kod != null) {
                    obj.put("nama", kod.getDesc());
               }
          }
          return new StreamingResolution("application/json", obj.toString());
     }

     @HandlesEvent("req_kat_sekolah_desc")
     public Resolution kategoriSekolahDescInquiry() {

          String kodJenis = getContext().getRequest().getParameter("param1");
          JSONObject obj = new JSONObject();

          KodJenisSekolah kod = kodJenisSekolahDAO.findById(kodJenis);
          if (kod != null) {
               obj.put("nama", kod.getNama());
          }
          return new StreamingResolution("application/json", obj.toString());
     }

     @HandlesEvent("req_sekolah_desc")
     public Resolution sekolahDescInquiry() {

          String kodJenis = getContext().getRequest().getParameter("param1");
          JSONObject obj = new JSONObject();

          KodSekolah kod = kodSekolahDAO.findById(kodJenis);
          if (kod != null) {
               obj.put("nama", kod.getNama());
          }
          return new StreamingResolution("application/json", obj.toString());
     }

     @HandlesEvent("req_all_jenis_sekolah")
     public Resolution jenisSekolahInquiry() {
          List<KodJenisSekolah> list = listUtil.getSenaraiJenisSekolah();

          JSONArray array = new JSONArray();
          for (KodJenisSekolah kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("kod", kod.getKod());
               obj.put("nama", kod.getNama());
               array.put(obj);
          }

          return new StreamingResolution("application/json", array.toString());
     }

     @HandlesEvent("req_all_sekolah")
     public Resolution sekolahnquiry() {
          List<KodSekolah> list = listUtil.getSenaraiSekolah();

          JSONArray array = new JSONArray();
          for (KodSekolah kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("kod", kod.getKod());
               obj.put("nama", kod.getNama());
               array.put(obj);
          }

          return new StreamingResolution("application/json", array.toString());
     }

     @HandlesEvent("sekolah_negeri_enq")
     public Resolution sekolahBasedOnNegeriInquiry() {

          String kodNegeri = getContext().getRequest().getParameter("param1");
          String jenisSekolah = getContext().getRequest().getParameter("param2");

          JSONArray array = new JSONArray();

          List<KodSekolah> list = listUtil.getSenaraiSekolah(jenisSekolah, kodNegeri);
          for (KodSekolah kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("kod", kod.getKod());
               obj.put("nama", kod.getNama());
               array.put(obj);
          }
          return new StreamingResolution("application/json", array.toString());
     }

     @HandlesEvent("req_all_universiti")
     public Resolution universitiInquiry() {

          List<KodUniversiti> list = listUtil.getSenaraiUniversiti();

          JSONArray array = new JSONArray();
          for (KodUniversiti kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("kod", kod.getKod());
               obj.put("nama", kod.getNama());
               array.put(obj);
          }
          return new StreamingResolution("application/json", array.toString());
     }

     @HandlesEvent("req_all_jenis_pengajian")
     public Resolution jenisPengajianInquiry() {

          List<KodJenisPengajian> list = listUtil.getSenaraiJenisPengajian();

          JSONArray array = new JSONArray();
          for (KodJenisPengajian kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("kod", kod.getKod());
               obj.put("nama", kod.getNama());
               array.put(obj);
          }
          return new StreamingResolution("application/json", array.toString());
     }

     @HandlesEvent("req_all_peringkat_pengajian")
     public Resolution peringkatPengajianInquiry() {

          List<KodTahapPengajian> list = listUtil.getSenaraiTahapPengajian();

          JSONArray array = new JSONArray();
          for (KodTahapPengajian kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("kod", kod.getKod());
               obj.put("nama", kod.getNama());
               array.put(obj);
          }
          return new StreamingResolution("application/json", array.toString());
     }

     @HandlesEvent("req_all_fakulti")
     public Resolution fakultiInquiry() {

          List<KodFakulti> list = listUtil.getSenaraiFakulti();

          JSONArray array = new JSONArray();
          for (KodFakulti kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("kod", kod.getKod());
               obj.put("nama", kod.getNama());
               array.put(obj);
          }
          return new StreamingResolution("application/json", array.toString());
     }
     
     @HandlesEvent("req_course_center")
     public Resolution courseCenterInquiry() {
          List<PusatKos> list = listUtil.getPusatKos();

          JSONArray array = new JSONArray();
          for (PusatKos kod : list) {
               JSONObject obj = new JSONObject();
               obj.put("value", kod.getKod());
               obj.put("name", kod.getNama());
               array.put(obj);
          }

          return new StreamingResolution("application/json", array.toString());
     }

     @HandlesEvent("req_tac")
     public Resolution tacInquiry() {

          String m_error = "";

          String amaun = getContext().getRequest().getParameter("amaun");
          String noAkaun = getContext().getRequest().getParameter("noAkaun");
          String noKp = getContext().getRequest().getParameter("noKp");
          String akaunDari = getContext().getRequest().getParameter("akaunDari");
          String noKpDari = getContext().getRequest().getParameter("noKpDari");

          String sts = getContext().getRequest().getParameter("sts");

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));
          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
          Deposit deposit = new Deposit();
          deposit.setNoAkaun(noAkaun);
          deposit.setNoAkaunDari(akaunDari);
          deposit.setNoKp(noKp);
          deposit.setNoKpDari(noKpDari);

          boolean check = checking.checkAcc(deposit, userId);
//
          if (!check) {
               return new StreamingResolution("text/plain", "NO AKAUN / PENGENALAN TIDAK SAH!!");
          }

          SessionManager sm = SessionManager.getInstance();

          LoginSession ls = sm.getActiveSessionByUserId(userId);

          if (ls != null && ls.getSessionId().equals(sessionId)) {
               TrxAuthorizationCodeActionBean action
                       = ableContextListener.newInstance(TrxAuthorizationCodeActionBean.class);
               SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
               String dtStr = sdf.format(new Date());

               StringBuilder msg = new StringBuilder();
               if ("2".equals(sts)) {
                    msg = new StringBuilder("mytaha online: Pindahan Simpanan RM")
                            .append(amaun)
                            .append(" pada ")
                            .append(dtStr);
               } else if ("1".equals(sts)) {
                    msg = new StringBuilder("mytaha online: Kemaskini Favourite Account TH");
               }
               Pengguna pengguna = user.findUserByIdUser(userId);

               action.setPengguna(pengguna);

               String results = action.GenerateTac(HEADER_ID_FND_TFR, msg.toString(), sessionId);

               String[] result = results.split(",");
               if (result[0].trim().equals("200")) {
                    JSONObject json = new JSONObject();
                    json.put("noTel", result[1].substring(0, result[1].length() - 3).concat("xxx"));
                    json.put("date", new Date());

                    return new StreamingResolution("application/json", json.toString());

               } else {
                    m_error = "Kod Kebenaran Transaksi tidak berjaya di hantar buat masa ini. Sila cuba semula";
                    return new StreamingResolution("text/plain", m_error);
               }

          } else {
               return new StreamingResolution("text/plain", "ID Sessi TIDAK SAH!!");
          }
     }
     
     @HandlesEvent("req_profile_tac")
     public Resolution upProfileTac() { 
         
        String m_error = "";

          String noAkaun = getContext().getRequest().getParameter("noAkaun");
          String noKp = getContext().getRequest().getParameter("noKp");
          String akaunDari = getContext().getRequest().getParameter("akaunDari");
          String noKpDari = getContext().getRequest().getParameter("noKpDari");

          String cookie = getContext().getRequest().getHeader("Cookie");
          String userId = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf(":"));
          String sessionId = cookie.substring(cookie.indexOf(":") + 1);

          AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
          Deposit deposit = new Deposit();
          deposit.setNoAkaun(noAkaun);
          deposit.setNoAkaunDari(akaunDari);
          deposit.setNoKp(noKp);
          deposit.setNoKpDari(noKpDari);

          boolean check = checking.checkAcc(deposit, userId);
//
          if (!check) {
               return new StreamingResolution("text/plain", "NO AKAUN / PENGENALAN TIDAK SAH!!");
          }

          SessionManager sm = SessionManager.getInstance();

          LoginSession ls = sm.getActiveSessionByUserId(userId);
 
         if (ls != null && ls.getSessionId().equals(sessionId)) {
               TrxAuthorizationCodeActionBean action
                       = ableContextListener.newInstance(TrxAuthorizationCodeActionBean.class);
               SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
               String dtStr = sdf.format(new Date());

               StringBuilder sb = new StringBuilder(" mytaha online: Kemaskini profil TH");
               Pengguna pengguna = user.findUserByIdUser(userId);

               action.setPengguna(pengguna);

               String results = action.GenerateTac(HEADER_ID_UPD_PROFILE, sb.toString(), sessionId);

               String[] result = results.split(",");
               if (result[0].trim().equals("200")) {
                    JSONObject json = new JSONObject();
                    json.put("noTel", result[1].substring(0, result[1].length() - 3).concat("xxx"));
                    json.put("date", new Date());

                    return new StreamingResolution("application/json", json.toString());

               } else {
                    m_error = "Kod Kebenaran Transaksi tidak berjaya di hantar buat masa ini. Sila cuba semula";
                    return new StreamingResolution("text/plain", m_error);
               }

          } else {
               return new StreamingResolution("text/plain", "ID Sessi TIDAK SAH!!");
          }
  
    }

     @HandlesEvent("req_user_info")
     public Resolution requestUserInfo() {

          String noAkaun = getContext().getRequest().getParameter("noAkaun");
          String noPengenalan = getContext().getRequest().getParameter("noKp");          

          Pengguna pengguna = userManager.findUser(noPengenalan, noAkaun);

          if (pengguna == null) {
               return new StreamingResolution("text/plain", "Pengguna tidak dijumpai.");
          } 
          
          JSONObject obj = new JSONObject();
          obj.put("userId", pengguna.getIdPengguna());
          obj.put("nama", pengguna.getNama());
          obj.put("status", pengguna.getActive() == 'Y' ? "Aktif" : "Tidak Aktif");
          
          return new StreamingResolution("application/json", obj.toString());
     }
     
     @HandlesEvent("req_validate_userId")
     public Resolution requestValidateUserInfo() {

          String userId = getContext().getRequest().getParameter("userId");
          

          Pengguna pengguna = userManager.findUserByIdUser(userId);

          if (pengguna == null) {
               return new StreamingResolution("text/plain", "Pengguna tidak dijumpai.");
          } 
          
          JSONObject obj = new JSONObject();
          obj.put("userId", pengguna.getIdPengguna());
          obj.put("image", pengguna.getImgid());         
          
          return new StreamingResolution("application/json", obj.toString());
     }
     

     public String toJson() {
          return "";
     }

}
